import {ipconfig} from "./ipconfig";

/**
 * 获取用户登录信息
 */
export const getUser = (vue,fullPath) => {
  let userJson = window.localStorage.getItem('user');
  if(userJson){
    let user = JSON.parse(userJson);
    if(user.expTime && user.expTime>new Date().getTime()){
      setUser(user);
      return user;
    }else {
      window.localStorage.removeItem('user');
      return null;
    }
  }
  // debugger;
  if(vue){
    if(isWeiXin()){
      let toUrl=ipconfig.wxWebAuthUrl+'#/login?redirect='+encodeURIComponent(fullPath);
      toUrl = encodeURIComponent(toUrl);
      let weUrl =getStore('weUrl');
      weUrl=weUrl.replace('-URL-',toUrl);
      console.log(fullPath,weUrl);
      window.location.href = weUrl;
      return;
    }
    vue.$router.push({name:'login',query:{redirect:fullPath}});
  }
  return null;
};
/**
 * 存储用户登录信息
 */
export const setUser = user => {
  if(user){
    user.expTime = new Date().getTime() + 30*60*1000;
    window.localStorage.setItem('user',JSON.stringify(user));
  }
};
/**
 * 存储sessionStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
};
/**
 * 获取sessionStorage
 */
export const getStore = name => {
  if (!name) return;
  return window.sessionStorage.getItem(name);
};
/**
 * 删除sessionStorage
 */
export const removeStore = name => {
  if (!name) return;
  window.sessionStorage.removeItem(name);
};
/**
 * 清空sessionStorage
 */
export const clearStore = () => {
  window.sessionStorage.clear();
};
/*********************localStorage**************************/
/**
 * 存储localStorage
 */
export const setlocalStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};
/**
 * 获取localStorage
 */
export const getlocalStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
};
/**
 * 删除localStorage
 */
export const removelocalStore = name => {
  if (!name) return;
  window.localStorage.removeItem(name);
};
/**
 * 清空localStorage
 */
export const clearlocalStore = () => {
  if (!name) return;
  window.localStorage.clear();
};

/**
 * 判断是否为手机号
 */
export const isPoneAvailable = str =>{
  let myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (!myreg.test(str)) {
    return false;
  } else {
    return true;
  }
};

/**
 * 获取地址栏参数
 */
export const getRequest = () =>{
  let url = window.location.search; //获取url中"?"符后的字串
  let theRequest = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
    }
  }
  return theRequest;
};

/**
 * 判断是否微信 是不是微信浏览器
 */
export const isWeiXin = () => {
  let ua = window.navigator.userAgent.toLowerCase();
  if(ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
};

/**
 * 判断是安卓还是ios
 */
export const isAndroid = () => {
  let ua = navigator.userAgent.toLowerCase();
  if (/iphone|ipad|ipod/.test(ua)) {
    return false;
  } else if (/android/.test(ua)) {
    return true;
  }
};

/**
 * 根据key取得对应的statusMap信息
 */
export const getStatusMapByKey = key => {
  let commonStatus = JSON.parse(getlocalStore('commonStatus'));
  let statusInfo = commonStatus[key];
  if(!statusInfo) {
    debugger;
  }
  return statusInfo.statusMap;
};
/**
 * 根据key取得对应的status信息
 */
export const getStatusByKeyVal = (key, val) => {
  let statusMap = getStatusMapByKey(key);
  for(let key in statusMap) {
    if(statusMap[key].val == val) {
      return statusMap[key];
    }
  }
  return {
    val: "",
    name: "",
    dispName: ""
  };
};

/******************密码强度验证*****************/
/**
 * 判断输入密码的类型
 */
function CharMode(iN){
  if (iN>=48 && iN <=57) //数字
    return 1;
  if (iN>=65 && iN <=90) //大写
    return 2;
  if (iN>=97 && iN <=122) //小写
    return 4;
  else
    return 8;
}
/**
 * bitTotal函数
 * 计算密码模式
 */
function bitTotal(num){
  let modes=0;
  for (let i=0;i<4;i++){
    if (num & 1) modes++;
    num>>>=1;
  }
  return modes;
}
/**
 * 返回强度级别
 */
export const checkStrong = (sPW) => {
  if (sPW.length<6)
    return 0; //密码太短，不检测级别
  let Modes=0;
  for (let i=0;i<sPW.length;i++){
    //密码模式
    Modes|=CharMode(sPW.charCodeAt(i));
  }
  return bitTotal(Modes);
};
/**
 * 显示颜色
 */
export const pwStrength = (id_L,id_M,id_H,pwd) => {
  let Dfault_color="#eeeeee";     //默认颜色
  let L_color="#FF0000";      //低强度的颜色，且只显示在最左边的单元格中
  let M_color="#FF9900";      //中等强度的颜色，且只显示在左边两个单元格中
  let H_color="#33CC00";    //高强度的颜色，三个单元格都显示
  let Lcolor,Mcolor,Hcolor;
  if (pwd==null||pwd==''){
    Lcolor=Mcolor=Hcolor=Dfault_color;
  }
  else{
    let S_level=checkStrong(pwd);
    switch(S_level) {
      case 0:
        // Lcolor=Mcolor=Hcolor=Dfault_color;
        Lcolor=L_color;
        Mcolor=Hcolor=Dfault_color;
        break;
      case 1:
        Lcolor=L_color;
        Mcolor=Hcolor=Dfault_color;
        break;
      case 2:
        Lcolor=Mcolor=M_color;
        Hcolor=Dfault_color;
        break;
      default:
        Lcolor=Mcolor=Hcolor=H_color;
    }
  }
  // console.log(id_L.style.background);
  id_L.style.background=Lcolor;
  id_M.style.background=Mcolor;
  id_H.style.background=Hcolor;
  // document.getElementById(id_L).style.background=Lcolor;
  // document.getElementById(id_M).style.background=Mcolor;
  // document.getElementById(id_H).style.background=Hcolor;
  return;
};

/**
 * 判断字符长度 汉字算两个字符
 */
export const getByteLen = (val) =>{
  let len = 0;
  for (let i = 0; i < val.length; i++) {
    let length = val.charCodeAt(i);
    if(length>=0&&length<=128)
    {
      len += 1;
    }
    else
    {
      len += 2;
    }
  }
  return len;
};

/**
 * 文本框根据输入内容自适应高度
 * @param                {HTMLElement}        输入框元素
 * @param                {Number}                设置光标与输入框保持的距离(默认0)
 * @param                {Number}                设置最大高度(可选)
 */
export const autoTextarea = (elem, extra, maxHeight) => {
  extra = extra || 0;
  var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
    isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
    addEvent = function (type, callback) {
      elem.addEventListener ?
        elem.addEventListener(type, callback, false) :
        elem.attachEvent('on' + type, callback);
    },
    getStyle = elem.currentStyle ? function (name) {
      var val = elem.currentStyle[name];

      if (name === 'height' && val.search(/px/i) !== 1) {
        var rect = elem.getBoundingClientRect();
        return rect.bottom - rect.top -
          parseFloat(getStyle('paddingTop')) -
          parseFloat(getStyle('paddingBottom')) + 'px';
      };

      return val;
    } : function (name) {
      return getComputedStyle(elem, null)[name];
    },
    minHeight = parseFloat(getStyle('height'));

  elem.style.resize = 'none';

  var change = function () {
    var scrollTop, height,
      padding = 0,
      style = elem.style;

    if (elem._length === elem.value.length) return;
    elem._length = elem.value.length;

    if (!isFirefox && !isOpera) {
      padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
    };
    scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

    elem.style.height = minHeight + 'px';
    if (elem.scrollHeight > minHeight) {
      if (maxHeight && elem.scrollHeight > maxHeight) {
        height = maxHeight - padding;
        style.overflowY = 'auto';
      } else {
        height = elem.scrollHeight - padding;
        style.overflowY = 'hidden';
      };
      style.height = height + extra + 'px';
      scrollTop += parseInt(style.height) - elem.currHeight;
      document.body.scrollTop = scrollTop;
      document.documentElement.scrollTop = scrollTop;
      elem.currHeight = parseInt(style.height);
    };
  };

  addEvent('propertychange', change);
  addEvent('input', change);
  addEvent('focus', change);
  change();
};

/**
 * 分割视频时间
 */
export const timeStamp = (second_time) => {
  let time1 = ((parseInt(second_time) / 100)).toString();
  let time2 = time1.split(".")[1] ? (time1.split(".")[1].length == 1 ? time1.split(".")[1] + '0' : time1.split(".")[1]) : '00';
  let time = '00' + ':' + time2;
  if (parseInt(second_time) > 60) {
    let second = ((parseInt(second_time) % 60) / 100).toString();
    let min = (parseInt(second_time / 60) / 100).toString();
    let time3 = second.split(".")[1] ? (second.split(".")[1].length == 1 ? second.split(".")[1] + '0' : second.split(".")[1]) : '00';
    let time4 = min.split(".")[1] ? (min.split(".")[1].length == 1 ? min.split(".")[1] + '0' : min.split(".")[1]) : '00';
    time = time4 + ":" + time3;
  }
  return time;
};

/**
 * 日期时间戳
 */
export const timeMsec = (value) => {
  //2018-05-24 14:46:36
  value = value.replace(/-/g,'/');
  let data = new Date(value);
  return data.getTime();
};

/**
 * 模态框显示时
 * 禁止滑动
 */
export const stop = () => {
  document.body.style.overflow = 'hidden';
  document.addEventListener("touchmove", mo, false);//禁止页面滑动
};
/***取消滑动限制***/
export const move = () => {
  document.body.style.overflow = '';//出现滚动条
  document.removeEventListener("touchmove", mo, false);
};
let mo = (e) => {
  e.preventDefault();
};



